﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Winter.BackEnd.Models.Domain;
using System.Security.Principal;
using System.Net.Mail;
using System.Web.Mail;

namespace Winter.BackEnd.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {

        #region Properties
        public IMembershipService MembershipService
        {
            get;
            private set;
        }

        public IFormsAuthentication FormsAuth
        {
            get;
            private set;
        }
        #endregion

        #region Constructors
        public HomeController()
            : this(null, null)
        {
        }

        public HomeController(IFormsAuthentication formsAuth, IMembershipService service)
        {
            FormsAuth = formsAuth ?? new FormsAuthenticationService();
            MembershipService = service ?? new AccountMembershipService();
        }
        #endregion

        #region Actions
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Index()
        {
            ViewData["Title"] = "Register";
            return View();
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Recovery()
        {

            return View();
        }
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Recovery(string email)
        {///DEMO
            System.Web.Mail.MailMessage message = new System.Web.Mail.MailMessage();
            message.To = email;
            message.From = "hkostya@gmail.com";
            message.Body = Membership.GetUser(Membership.GetUserNameByEmail(email)).ResetPassword();
            SmtpMail.SmtpServer = "gmail.com";
            SmtpMail.Send(message);
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult ChangePassword(string oldPassword, string newPassword, string confirmPassword)
        {
            if (newPassword.Equals(confirmPassword) && new AccountMembershipService().ChangePassword(User.Identity.Name, oldPassword, newPassword))
            {
                return Redirect("ChangedPasswordSuccess");
            }
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Index(string login, string password, string returnUrl)
        {
            if (IsValidLoginArgument(login, password))
            {
                if (Membership.ValidateUser(login, password))
                {
                    return Redirect(this.RedirectFromLoginPage(login, returnUrl));
                }
                else
                {
                    this.ViewData["LoginFailed"] = "Login failed. Make sure you have entered correct login and password.";
                }
            }
            return View();
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult LogOut()
        {
            FormsAuth.SignOut();
            return Redirect(FormsAuthentication.LoginUrl);
        }
        #endregion

        #region HelerMethods
        private string RedirectFromLoginPage(string userName, string ReturnUrl)
        {
            FormsAuth.SignIn(userName, false);
            if (!string.IsNullOrEmpty(ReturnUrl))
            {
                return ReturnUrl;
            }
            else
            {
                return FormsAuthentication.DefaultUrl;
            }
        }

        private bool IsValidLoginArgument(string userName, string password)
        {
            return !(string.IsNullOrEmpty(userName) && string.IsNullOrEmpty(password));
        }
        #endregion

    }

    #region HelperTypes
    public interface IFormsAuthentication
    {
        void SignIn(string userName, bool createPersistentCookie);
        void SignOut();
    }

    public class FormsAuthenticationService : IFormsAuthentication
    {
        public void SignIn(string userName, bool createPersistentCookie)
        {
            FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
            Repository.CurrentUser = Repository.CurrentDataContext.aspnet_Users.Single(u => u.UserName.ToLower() == userName.ToLower());
        }
        public void SignOut()
        {
            FormsAuthentication.SignOut();
        }
    }

    public interface IMembershipService
    {
        int MinPasswordLength { get; }

        bool ValidateUser(string userName, string password);
        MembershipCreateStatus CreateUser(string userName, string password, string email);
        bool ChangePassword(string userName, string oldPassword, string newPassword);
    }

    public class AccountMembershipService : IMembershipService
    {
        private MembershipProvider _provider;

        public AccountMembershipService()
            : this(null)
        {
        }

        public AccountMembershipService(MembershipProvider provider)
        {
            _provider = provider ?? Membership.Provider;
        }

        public int MinPasswordLength
        {
            get
            {
                return _provider.MinRequiredPasswordLength;
            }
        }

        public bool ValidateUser(string userName, string password)
        {
            return _provider.ValidateUser(userName, password);
        }

        public MembershipCreateStatus CreateUser(string userName, string password, string email)
        {
            MembershipCreateStatus status;
            _provider.CreateUser(userName, password, email, null, null, true, null, out status);
            return status;
        }

        public bool ChangePassword(string userName, string oldPassword, string newPassword)
        {
            MembershipUser currentUser = _provider.GetUser(userName, true /* userIsOnline */);
            return currentUser.ChangePassword(oldPassword, newPassword);
        }
    }
    #endregion
}
